<?php

namespace App\Http\Controllers;

use App\Models\MchOrder;
use App\Models\Member;
use App\Models\Red;
use EasyWeChat\Kernel\Exceptions\Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Kuyuan\Phpwidget\Str;

/**
 * 发红包
 * Class SendRedController
 * @package App\Http\Controllers
 */
class SendRedController extends Controller
{
    // 红包对象
    private $Red = null;

    // 会员id
    private $_member_id = 0;

    // 配置
    private $Setting = null;

    // 请求参数
    private $data = null;

    public function index(Request $request)
    {
        $this->Setting = $this->getConfig();
        $this->data = $request->input();
        $this->_member_id = auth('member')->id();
        DB::beginTransaction();
        try {
            // 红包最低金额验证
            $_check_low_money = $this->checkLowRedMoney();
            if ($_check_low_money !== true) {
                throw new \PDOException($_check_low_money['message'], $_check_low_money['code']);
            }
            // 新增红包
            $_red_insert_data = $request->input();
            $_red_insert_data['member_id'] = auth('member')->id();
            $_red_insert_data['pay'] = Str::format_money($_red_insert_data['pay'],true);
            $_red_insert_data['money'] = Str::format_money($_red_insert_data['money'],true);
            $_red_insert_data['charge'] = Str::format_money($_red_insert_data['charge'],true);
            $_red_insert_data['answer'] = [
                'question' => $_red_insert_data['question'],
                'choice_question' => $_red_insert_data['choice_question'],
                'answer_question' => $_red_insert_data['answer_question']
            ];
            $_red_insert_data['start_time'] = $_red_insert_data['end_time'] = [
                'time_type' => $_red_insert_data['time_type'],
                'time' => $_red_insert_data['time']
            ];
            $this->Red = Red::create($_red_insert_data);

            // 支付红包金额
            $_pay = $this->pay();
            if($_pay['code'] != 200) {
                throw new \PDOException($_pay['message'],$_pay['code']);
            }
            if($this->Red->pay_type === 1) {
                $_result = ['data'=>$this->Red->id];
            } else {
                $_result = ['data'=>$this->Red->id,'pay_params'=>$_pay['data']];
            }
            DB::commit();
            return response($_result);
        } catch (\PDOException $e) {
            DB::rollBack();
            return response(['message' => $e->getMessage(), 'code' => $e->getCode()]);
        }
    }

    /**
     * 验证红包最低总额
     */
    private function checkLowRedMoney()
    {
        if ($this->Setting->low_red_money > 0) {
            $_red_total = $this->data['pay'] - $this->data['charge'];
            if ($_red_total < $this->Setting->low_red_money) {
                return array("code" => 402, "message" => "红包总额不能低于" . $this->Setting->low_red_money . "元");
            }
        }
        return true;
    }

    /**
     * 支付发红包金额，并且返回支付参数
     */
    private function pay()
    {
        // 判断是否支持余额发红包,并且判断用户余额是否足够
        if ($this->Setting->finance->balance_send
            &&
            $this->balance() >= $this->Red->pay
        ) {
            // 用户余额足够，扣除用户余额
            return $this->expend();
        } else {
            // 获取微信支付参数
            return $this->getWxPayParams();
        }
    }

    /**
     * 扣除余额
     */
    private function expend()
    {
        $_balance_handle = $this->balanceHandle(
            $this->Red->pay,
            false
        );
        if($_balance_handle) {
            $this->Red->status = 2;
            $this->Red->pay_type = 1;
            if($this->Red->save()) {
                return ['code'=>200];
            }
        }
        return ['code'=>402];
    }

    /**
     * 获取微信支付参数
     */
    private function getWxPayParams()
    {
        $_order_id = $this->createMchOrder();
        if(!$_order_id) return false;
        try {
            $wechatPay = $this->wechatPay();
            $_result = $wechatPay->order->unify([
                'body' => $this->Setting->website_name.'发红包',
                'out_trade_no' => $_order_id,
                'total_fee' => $this->Red->pay,
                'trade_type' => 'JSAPI',
                'openid' => Member::where('id',$this->_member_id)->value('openid')
            ]);
            if($_result['return_code'] != 'SUCCESS' || $_result['result_code'] != 'SUCCESS') {
                throw new Exception($_result['err_code_des'],402);
            }
            $Jssdk = $wechatPay->jssdk;
            return ['data'=>$Jssdk->sdkConfig($_result['prepay_id']),'code'=>200];
        } catch (Exception $e) {
            return ['message'=>$e->getMessage(),'code'=>$e->getCode()];
        }
    }

    /**
     * 创建商户订单
     * @return bool
     */
    private function createMchOrder()
    {
        $_order_id = (string) mt_rand(10000,99999).time();
        $MchOrder = MchOrder::where('order_id',$_order_id)->first();
        if($MchOrder) return $this->createMchOrder();
        $MchOrder = MchOrder::create([
            'member_id' => $this->_member_id,
            'order_id' => $_order_id,
            'money' => $this->Red->pay,
            'source_id' => $this->Red->id
        ]);
        if($MchOrder) {
            return $MchOrder->order_id;
        } else {
            return false;
        }
    }
}
